package com.hx.myfristandriod;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class TestFileActivity extends Activity {
    
	    private EditText txtMessage;
	    private Button btnSave;
	    private Button btnOpen;
	    @Override
		protected void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.file_test);
	        
	        txtMessage=(EditText) findViewById(R.id.txtMessage);
	        btnSave=(Button) findViewById(R.id.btnSave);
	        btnSave.setOnClickListener(new ViewFileOcl());
	        btnOpen=(Button) findViewById(R.id.btnOpen);
	        btnOpen.setOnClickListener(new ViewFileOcl());
	    }

	    //btnOpen,btnSave绑定监听事件，单击调用
  class ViewFileOcl  implements OnClickListener {
	@Override
	public void onClick(View v) {
      switch (v.getId()) {
	       case R.id.btnSave:
	    	   String txtMsg=txtMessage.getText().toString().trim();
	        	FileOutputStream fos = null;
					try {
						fos = openFileOutput("message.txt", MODE_APPEND);
						   fos.write(txtMsg.getBytes());
						   fos.close();
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
					Toast.makeText(getApplicationContext(), "文件写入成功", Toast.LENGTH_LONG).show();
			 break;
	       case R.id.btnOpen:
						try {
							FileInputStream fis=openFileInput("message.txt");
							byte[] buffer=new byte[fis.available()];
					    	fis.read(buffer);
					    	Toast.makeText(getApplicationContext(), "读取信息："+new String(buffer), Toast.LENGTH_LONG).show();
					    	fis.close();
						} catch (FileNotFoundException e) {
							e.printStackTrace();
						} catch (IOException e) {
							e.printStackTrace();
						}
					    	   
				 break;
	  	default:
			break;
         	}
	  } 
  }
  
}
